package com.xujiang.mytool;

import android.support.multidex.MultiDexApplication;

import com.xujiang.common_core.Common;
import com.xujiang.common_core.util.ourexception.NetException;
import com.xujiang.common_core.util.ourexception.NetLocalException;
import com.xujiang.common_core.util.ourexception.NetServerException;
import com.xujiang.common_core.util.ourexception.SystemContentException;
import com.xujiang.common_core.util.ourexception.SystemException;
import com.xujiang.common_core.util.tool.JsonUtils;
import com.xujiang.common_plus.util.OkHttp3Utils;
import com.xujiang.data.Data;
import com.xujiang.data.GlobalConstants;
import com.xujiang.data.model.ServerError;

import org.json.JSONException;

import java.io.IOException;
import java.util.Map;

import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * @author xujiang
 * @version 2017-07-04 09:50
 *          <p>
 *          compile 'com.android.support:multidex:1.0.1'
 */
public class MApplication extends MultiDexApplication {
    private final String TAG = MApplication.class.getSimpleName();
    OkHttp3Utils.Init init;

    @Override
    public void onCreate() {
        super.onCreate();
        Common.init(this, GlobalConstants.PROJECT_NAME, BuildConfig.DEBUG);
        OkHttp3UtilsInit();
        //Data.init(getApplicationContext(),GlobalConstants.PROJECT_NAME, init);  //有证书
        Data.init(GlobalConstants.BASE_HTTP_SERVER_ADDRESS, init);  //无证书
    }

    public void OkHttp3UtilsInit() {
        init = OkHttp3Utils.init().setErrorHandleListener(new OkHttp3Utils.ErrorHandleListener() {

            @Override
            public Response checkError(Response response) throws NetException {
                //每个使用OkHttpUtils的请求都会检查
                if (response.isSuccessful()) {
                    //对服务器本身的错误做处理
                    boolean sys404 = false;
                    if (response.code() == 404) {
                        sys404 = true;
                    } else if (response.code() == 502) {
                        throw new NetLocalException(getString(R.string.ERR_SERVER) + "502");
                    }

                    ServerError error;
                    try {
                        ResponseBody body = response.body();
                        if (body == null) {
                            throw new NetLocalException(getString(R.string.ERR_SERVER),
                                    new SystemContentException("ResponseBody is null"));
                        }
                        String json = body.string();
                        error = JsonUtils.parse(json, "error", ServerError.class);
                    } catch (IOException e) {
                        e.printStackTrace();
                        error = null;
                    } catch (SystemException e) {
                        error = null;
                        if (sys404 && e.getCause() instanceof JSONException) {
                            throw new NetLocalException(getString(R.string.ERR_SERVER) + " 404");
                        } else {
                            throw new NetLocalException(getString(R.string.ERR_SERVER), e);
                        }
                    }
                    assert error != null;
                    throw new NetServerException(error.getMsg(), error);
                }
                return response;
            }
        }).addHeaderPlus(new OkHttp3Utils.HeaderPlusListener() {

            @Override
            public Request.Builder headerInterceptor(Request originalRequest, Request.Builder builder,
                                                     Map<String, Object> parameters) {
                if (true) {//只要登录就会添加header信息
                    builder.addHeader("tk", "token");
                    builder.addHeader("accountID", "userId");
                    builder.addHeader("tz", "tz");
                }
                return builder;
            }
        });
    }
}
